//
//  WmcLastWatermarkDBManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/13.
//

import HandyJSON
import YPBedrock

// MARK: - 扩展WmcLastWatermarkDBManager + WmcDBProtocol

extension WmcLastWatermarkDBManager: WmcDBProtocol {
    /// 表名
    static var tableName: String = "last_use_watermark"

    /// 表头数据列
    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(), // 主键
            .varchar(name: "watermark_detial_json"), // 水印的json数据
            .integer(name: "user_id"), // 用户信息 唯一信息 用于去重
            .date(name: "save_time"), // 存储时间
        ]
    }
}

// MARK: - [WmcLastWatermarkDBManager]

/// 存储用户最后一次使用的水印
struct WmcLastWatermarkDBManager {
    /// 存储最后使用的水印
    /// - Parameters:
    ///   - wm: 水印
    ///   - resultBlock: 结果
    static func setLastUseWatermark(_ wm: WmcWatermarkDetailModel,
                                    resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        // 转换json数据
        guard let watermarkJsonStr = wm.toJSONString() else { return }
        // 用户信息
        let userId: Int = 0
        // 查找是否有一样的数据
        WmcDBManager.shared.searchCustomData(tableName: tableName,
                                             condition: "where user_id = \"\(userId)\"") { list in
            if list.count >= 1 { // 有相同数据, 删除所有原数据
                list.forEach { dic in
                    if let id = dic["id"] as? Int {
                        WmcDBManager.shared.deleteData(tableName: tableName, id: id)
                    }
                }
            }
            // 再进行插入
            let date = WmcDateManager.shared.networkDate.value ?? Date()
            let dateValue = (date.timeIntervalSince1970).yp.int
            // 调用数据库
            WmcDBManager.shared.insertData(tableName: Self.tableName, insertData: [
                .init(column: Self.dataType[1], value: watermarkJsonStr),
                .init(column: Self.dataType[2], value: userId),
                .init(column: Self.dataType[3], value: dateValue),
            ], resultBlock: resultBlock)
        }
    }

    /// 搜索最后一次使用的水印
    /// - Parameter resultBlock: 结果
    static func searchLastUseWatermark(_ resultBlock: YPBlock.OneParam<WmcWatermarkDetailModel?>? = nil) {
        // 用户信息
        var userId: Int = 0
        if let _userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !_userId.isEmpty {
            userId = _userId.yp.int
        }
        WmcDBManager.shared.searchCustomData(tableName: tableName,
                                             condition: "where user_id = \"\(userId)\"") { list in
            guard !list.isEmpty, let first = list.first else { return }
            resultBlock?(parsingModel(first))
        }
    }

    /// 解析模型
    static func parsingModel(_ dic: [String: Any]) -> WmcWatermarkDetailModel? {
        // 解析
        if let wm_json = dic[Self.dataType[1].name] as? String {
            guard let dic = wm_json.yp.jsonObj as? [String: Any] else { return nil }
            return WmcWatermarkDetailModel.deserialize(from: dic)
        }
        return nil
    }
}
